package top.lixunda.ecommerce.server.auth.api.entity.dto;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import top.lixunda.ecommerce.server.auth.api.entity.cache.CacheAuthCode;
import top.lixunda.common.validate.annotation.*;

import java.time.LocalDateTime;
import java.util.Collections;

/**
 * 通用邮件验证码DTO
 *
 * @author Xumda
 * @version time:2019/12/17 15:28
 */
@ApiModel("通用邮件验证码DTO")
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class EmailGeneralCodeDTO {

    /**
     * 发送的账号
     */
    @ApiModelProperty(value = "发送的账号", notes = "不能为空，邮件地址格式")
    @XumNotNull
    @XumEmail(message = "不是一个合法的邮箱地址")
    private String email;

    /**
     * 发送的验证码
     */
    @ApiModelProperty(value = "发送的验证码", notes = "不能为空，4到6位字母或数字")
    @XumNotNull
    @XumRegex(value = "^[0-9a-zA-Z]{4,6}$", message = "验证码为4到6位字母或数字")
    private String code;

    /**
     * 执行的操作名称，如注册，登陆
     */
    @ApiModelProperty(value = "执行的操作名称", notes = "可以为空")
    @XumDefault("")
    @XumMax(10)
    private String action;

    /**
     * 失效时间，单位分钟
     */
    @ApiModelProperty(value = "失效时间", notes = "单位分钟，默认5分钟，最少一分钟")
    @XumDefault(numbers = 5)
    @XumMin(1)
    private Integer time;

    /**
     * 转化为AuthCodeCache
     *
     * @return CacheAuthCode
     */
    public CacheAuthCode toAuthCodeCache() {
        CacheAuthCode cacheAuthCode = new CacheAuthCode();
        cacheAuthCode.setAccounts(Collections.singletonList(this.email));
        cacheAuthCode.setAction(this.action);
        cacheAuthCode.setTime(LocalDateTime.now());
        cacheAuthCode.setLateTime(cacheAuthCode.getTime().plusMinutes(this.time));
        cacheAuthCode.setCode(this.code);
        cacheAuthCode.setType(CacheAuthCode.TYPE_EMAIL);
        return cacheAuthCode;
    }

}
